import axios,{AxiosRequestConfig} from 'axios'
import { userLoginStore} from "~/stores/userLogin";
import {signGengw} from "~/composables/md5";
import {router} from '~/plugins/router'
export const http = axios.create({
	baseURL: import.meta.env.VITE_API_BASE_URL,
})



// 添加请求拦截器
http.interceptors.request.use(
	function (config) {
		const userLogin = userLoginStore()
		config.headers.Authorization = userLogin.token
		// 在发送请求之前做些什么
		return config
	},
	function (error) {
		toast.warning(error.message ?? '未知请求错误')
		// 对请求错误做些什么
		return Promise.reject(error)
	},
)
// 添加响应拦截器
http.interceptors.response.use(
	function (response) {
		// 2xx 范围内的状态码都会触发该函数。
		// 对响应数据进行格式化
		let code = response.data.code
		switch (code) {
			case 401:
				toast.error("登录失效")
				router.push("/login")
				return Promise.reject(response.data.msg)
			case 300:
				toast.error(response.data.msg)
				return Promise.reject(response.data.msg)
			case 310:
				toast.error(response.data.msg)
				return Promise.reject(response.data.msg)
		}
		if (response.data) {
			return response.data
		}
		return response
	},
	function (error) {
		console.log("错误返回============>")
		const status = error.response?.status
		console.log(error.response)
		let { msg, message } = error.response?.data ?? {}
		if (!msg && message) {
			msg = message
		}

		if (!msg) {
			switch (status) {
				case 400:
					msg = '参数错误'
					break
				case 500:
					msg = '服务端错误'
					break
				case 404:
					msg = '路由未找到'
					break
				default:
					msg = error.message ?? '未知响应错误'
					break
			}
		}

		toast.warning(msg)
		// 超出 2xx 范围的状态码都会触发该函数。
		// 对响应错误做点什么
		return Promise.reject(error)
	},
)


// 封装 POST 请求
export const postRequest = (url: string, data?: any, config?: AxiosRequestConfig) => {
	return http.post(url, signGengw(data), config);
}
